#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cerrno>
#include <cstring>
#include <string>
#include <unistd.h>
#include "Log.hpp"
#include "Comm.hpp"
#include "nocopy.hpp"

const static int default_num = 5;

class TcpServer : public nocopy
{
public:
    TcpServer(const uint16_t port)
        : _port(port), _isRunning(false)
    {
    }

    void Init()
    {
        // 1.创建listensocket
        _listenSocket = socket(AF_INET, SOCK_STREAM, 0);
        if (_listenSocket < 0)
        {
            lg.LogMessage(Fatal, "_listensocket creat failure errno:%d strerr:%s\n",
                          errno, strerror(errno));
            exit(Socket_Err);
        }
        //解决一些bind失败的问题，进行socket选项配置
        int opt = 1;
        setsockopt(_listenSocket, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        lg.LogMessage(Debug, "create socket success, sockfd: %d\n", _listenSocket);

        // 2.bind
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = htonl(INADDR_ANY);
        int n = bind(_listenSocket, CONV(&local), sizeof(local));
        if (n != 0)
        {
            lg.LogMessage(Fatal, "bind failure errno:%d strerr:%s\n",
                          errno, strerror(errno));
            exit(Bind_Err);
        }

        //3. listen
        int l = listen(_listenSocket, default_num);
        if(l != 0)
        {
            lg.LogMessage(Warning,"listen Failure\n");
        }
        lg.LogMessage(Debug,"Listen success\n");

    }

    void Server(int socket)
    {
        char inbuffer[1024];
        while(_isRunning)
        {
            int n = read(socket,inbuffer,sizeof(inbuffer) - 1);
            if(n > 0)
            {
                inbuffer[n] = 0;
                std::cout << "client say#:" << inbuffer << std::endl;
                std::string response = "server say#:";
                response += inbuffer;
                write(socket,response.c_str(),response.size());
            }
            else if(n == 0)
            {
                lg.LogMessage(Warning,"client quit\n");
                return;
            }
            else
            {
                lg.LogMessage(Error,"read failure\n");
                return;
            }
        }
    }

    void Start()
    {
        _isRunning = true;
        while(_isRunning)
        {
            // 4.连接
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int socket = accept(_listenSocket,(struct sockaddr *)&(peer), &len);
            Server(socket);
            close(socket);
        }
    }

    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listenSocket;
    bool _isRunning;
};
